package com.common.utils.contract;

import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.entity.StringEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.common.base.utils.DateUtils;
import com.common.utils.ConstantPropUtil;
import com.common.utils.HttpClientUtils;

import net.sf.json.JSONObject;

/**
 * 合同生成工具，走前置
* @author 	zh
* @date 2018年1月25日
 */
public class ContractHttpUtils {

	private static Logger logger = LoggerFactory.getLogger(ContractHttpUtils.class);
	private static String appCd = ConstantPropUtil.getProperty("contract_sndAppCd");
	private static String url = ConstantPropUtil.getProperty("contract_url");
	
	/**
	 * post 请求生成pdf
	* @param params
	* @return
	* @return String    
	* @Author:   zh
	* @Create Date:   2018年1月25日
	 */
	@SuppressWarnings("rawtypes")
	public static String doPost(Map<String, Object> params){
		Map rs = getPublicKey(url, appCd);
		String modulus = GetModulus((String)rs.get("modulus"));
		String exponent = (String)rs.get("exponent");
		
		String api = ConstantPropUtil.getProperty("contract_api");
		String urlParam = "vt="+DateUtils.getDate("yyyyMMdd")+"&api="+api;
		RSAPublicKey publicKey= RSAUtils.getRSAPublidKey(modulus, exponent);
		String value = RSAUtils.encryptString(publicKey, urlParam);
		String urlSuff = "a=a" + BASE64Util.encode(appCd) + "&v=" + value;
		String realUrl = url + '?' + urlSuff;
		//发送的post格式按目标系统要求，这里的仅供参考
		String initPost = com.alibaba.fastjson.JSONObject.toJSONString(params, 
				SerializerFeature.WriteMapNullValue,
				SerializerFeature.WriteNullListAsEmpty,SerializerFeature.WriteNullStringAsEmpty);
		//必须步骤，须将post数据base64（如果是不需要base64，需要前置配置）
		String base64Str = BASE64Util.encode(initPost);
		StringEntity se = new StringEntity(base64Str,"utf-8");
		return HttpClientUtils.doPost(realUrl, se);
	}
	
	/**
	 * 获取公钥
	* @Title: getPublicKey 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param url 前置地址
	* @param @param appCd 发起系统id（需在前置注册）
	* @param @return modulus以及exponent（map类型）
	* @return Map    返回类型 
	* @throws
	 */
	@SuppressWarnings("rawtypes")
	public static Map getPublicKey(String url,String appCd){
		Map<String,Object> resultMap = new HashMap<String,Object>();
		Map<String,Object> rs = new HashMap<String,Object>();
		StringBuffer sb = new StringBuffer();
		sb.append(url+"?");
		sb.append("a=a"+BASE64Util.encode(appCd));
		sb.append("&i="+BASE64Util.encode("publicKey"));
		String result = HttpClientUtils.doGet(sb.toString(), null);
		//将pcl返回的数据直接返回给api
		resultMap = strToMap(result);
		if(resultMap.get("retCd").equals("0000")){
			rs.put("modulus", resultMap.get("modulus"));
			rs.put("exponent", resultMap.get("exponent"));
			return rs;
		}
		return null;
	}
	
	public static String GetModulus(String modulus) {
        String KeyC = modulus;
        if (modulus != null) {
            int count = modulus.length() / 100;
            StringBuffer sb = new StringBuffer(modulus);
            for (int i = 0; i <= count; i++) {
                sb.deleteCharAt(i * 100);
            }
            KeyC = sb.toString();
        } else {
        	logger.warn("modulus为空!");
        }
        return KeyC;
    }
	
	public static Map<String,Object> strToMap(String str){
		Map<String,Object> map=new HashMap<String, Object>();
		if(null ==str || str.equals("")){
			map.put("retCd", "9999");
			map.put("desc", "ESB无返回信息");
		}else{
			JSONObject json_ob = JSONObject.fromObject(str);
			@SuppressWarnings("rawtypes")
			Iterator it = json_ob.keys();
			// 遍历jsonObject数据，添加到Map对象  
		       while (it.hasNext()){  
		           String key = String.valueOf(it.next());  
		           Object value = json_ob.get(key);  
		           map.put(key, value);  
		       }  
		}
		return map;
	}
}

